package com.cskaoyan.bean.realm;

import com.cskaoyan.bean.MarketAdmin;
import com.cskaoyan.bean.MarketAdminExample;
import com.cskaoyan.bean.MarketUser;
import com.cskaoyan.bean.MarketUserExample;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.mapper.MarketUserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    MarketAdminMapper marketAdminMapper;
    @Autowired
    MarketUserMapper marketUserMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String host = token.getHost();
        if (host != null && "admin".equals(host)) {
            MarketAdminExample marketAdminExample = new MarketAdminExample();
            marketAdminExample.createCriteria().andUsernameEqualTo(username);
            List<MarketAdmin> marketAdmins = marketAdminMapper.selectByExample(marketAdminExample);
            if (marketAdmins.size() == 1) {
                MarketAdmin marketAdmin = marketAdmins.get(0);
                SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(marketAdmin, marketAdmin.getPassword(), getName());
                return simpleAuthenticationInfo;
            }
        } else {
            MarketUserExample marketUserExample = new MarketUserExample();
            marketUserExample.createCriteria().andUsernameEqualTo(username);
            List<MarketUser> marketUsers = marketUserMapper.selectByExample(marketUserExample);
            if (marketUsers.size() == 1) {
                MarketUser marketUser = marketUsers.get(0);
                SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(marketUser, marketUser.getPassword(), getName());
                return simpleAuthenticationInfo;
            }
        }
        return null;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
